package com.dlws.modules.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dlws.common.utils.IPUtils;
import com.dlws.modules.index.entity.Admin;

/**
 * 
  * 类简述
  * <p>
  *  用于过滤未登录用户
  * </p>
  * @Company 动力威视
  * @Copyright
  * @author (shx@sxw100.com)
  * @version 1.0
  * @CreateDate 2016年4月6日 下午1:43:51
 */
public class LoginFilter implements Filter {
	
	private Log log = LogFactory.getLog(getClass());
	//不需要过滤的地址,例:index.do
	//在web.xml中配置，多个以逗号隔开
	private String nofilterStr;

	public void init(FilterConfig cfg) throws ServletException {
		/** 获取web.xml配置的文件信息 */
		String str = cfg.getInitParameter("nofilterStr");
		if (!StringUtils.isBlank(str)) {
			nofilterStr = str;
		}
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		
		
		
		// 访问路径
		String servletPath = request.getServletPath();
		String login="/index/toLogin.do";
		
		Admin user=(Admin) session.getAttribute("user");
		System.out.println(request.getContextPath()+servletPath);
		String s[]=nofilterStr.split(",");
		
		log.info("请求链接：" + servletPath);
		log.info("请求参数：" + request.getQueryString());
		System.out.println("用户IP："+IPUtils.getIpAddr(request));
		
		boolean flag=false;
		for (int i = 0; i < s.length; i++) {
			if(servletPath.contains(s[i])){
				flag=true;
			}
		}
		if(flag){
			chain.doFilter(req, resp);
		}else{
			if(null!=user){
				chain.doFilter(req, resp);
			}else{
				response.sendRedirect(request.getContextPath()+login);
			}
		}
	}

	public void destroy() {
	}

}
